import config from '@/config/config'

// 常量定义
const AUTHORIZATION = 'authorization'
const PLATFORM = 'platform'
const USER_INFO = 'userInfo'

// 请求拦截器
const requestInterceptor = (options) => {
  if (!options.header) {
    options.header = {}
  }

  // 设置Content-Type
  switch (options.method) {
    case 'GET':
      options.header['Content-Type'] = 'application/x-www-form-urlencoded'
      break
    case 'POST':
    case 'PUT':
      options.header['Content-Type'] = 'application/json'
      break
    case 'DELETE':
      if (options.data && Object.keys(options.data).length > 0) {
        options.header['Content-Type'] = 'application/json'
      } else {
        options.header['Content-Type'] = 'application/x-www-form-urlencoded'
      }
      break
    default:
      options.header['Content-Type'] = 'application/json'
  }

  // 添加认证token
  const token = getToken()
  if (token) {
    options.header[AUTHORIZATION] = `${token}`
  }

  // 添加平台标识
  const platform = uni.getStorageSync(PLATFORM)
  if (platform) {
    options.header[PLATFORM] = platform
  }

  // 拼接完整URL
  if (options.url) {
    options.url = config.baseURL + options.url
  }

  return options
}

// 响应拦截器
const responseInterceptor = (response, resolve, reject) => {
  if (response.statusCode === 200) {
    if (response.data.code === 200 || response.data.success) {
      resolve(response.data.result || response.data.data || response.data)
    } else {
      uni.showToast({
        title: response.data.message || response.data.msg || '请求失败',
        icon: 'none'
      })
      reject(response.data)
    }
  } else {  
    let errorMsg = '请求失败'
    switch (response.statusCode) {
      case 401:
        if(response.data.message){
          errorMsg = response.data.message
        }else{
          errorMsg = '未授权，请重新登录'
        }
        clearToken()
        clearUserInfo()
        uni.reLaunch({ url:'/pages/login/login' })
        break
      case 403:
         if(response.data.message){
          errorMsg = response.data.message
        }else{
          errorMsg = '无权访问'
        }
        break
      case 404:
        errorMsg = '请求的资源不存在'
        break
      case 500:
        if(response.data.message){
          errorMsg = response.data.message
        }else{
          errorMsg = '服务器错误'
        }
        break
      default:
        errorMsg = `请求失败(${response.statusCode})`
    }

    uni.showToast({
      title: errorMsg,
      icon: 'none'
    })
    reject(response)
  }
}

// 核心请求方法
const request = (options = {}) => {
  return new Promise((resolve, reject) => {
    // 应用请求拦截器
    options = requestInterceptor(options)

    uni.request({
      ...options,
      timeout: config.timeout,
      success: (res) => {
        responseInterceptor(res, resolve, reject)
      },
      fail: (err) => {
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 导出请求方法
export default {
  // GET请求
  get(url, data = {}, options = {}) {
    const requestOptions = {
      url,
      method: 'GET',
      data,
      ...options
    }
    return request(requestOptions)
  },

  // POST请求
  post(url, data = {}, options = {}) {
    const requestOptions = {
      url,
      method: 'POST',
      data,
      ...options
    }
    return request(requestOptions)
  },

  // PUT请求
  put(url, data = {}, options = {}) {
    const requestOptions = {
      url,
      method: 'PUT',
      data,
      ...options
    }
    return request(requestOptions)
  },

  // DELETE请求
  delete(url, data = {}, options = {}) {
    const requestOptions = {
      url,
      method: 'DELETE',
      ...options
    }

    if (Object.keys(data).length > 0) {
      requestOptions.data = data
    }

    return request(requestOptions)
  },

  // 文件上传
  upload(url, filePath, options = {}) {
    return new Promise((resolve, reject) => {
      const fullUrl = config.baseURL + url

      // 设置headers
      const headers = {}
      const token = getToken()
      if (token) {
        headers[AUTHORIZATION] = `${token}`
      }

      const platform = uni.getStorageSync(PLATFORM)
      if (platform) {
        headers[PLATFORM] = platform
      }

      if (options.header) {
        Object.assign(headers, options.header)
      }

      uni.uploadFile({
        url: fullUrl,
        filePath: filePath,
        name: options.name || 'file',
        formData: options.formData || {},
        header: headers,
        timeout: config.timeout,
        success: (res) => {
          console.log('上传响应:', res)
          try {
            const data = JSON.parse(res.data)
            if (data.code === 200 || data.success) {
              resolve(data.result || data.data || data)
            } else {
              uni.showToast({
                title: data.message || data.msg || '上传失败',
                icon: 'none'
              })
              reject(data)
            }
          } catch (error) {
            console.error('解析上传响应失败:', error, res.data)
            uni.showToast({
              title: '服务器响应格式错误',
              icon: 'none'
            })
            reject(new Error('服务器响应格式错误'))
          }
        },
        fail: (error) => {
          console.error('上传请求失败:', error)
          uni.showToast({
            title: error.message,
            icon: 'none'
          })
          reject(new Error(errorMessage))
        }
      })
    })
  },

  // 自定义请求
  request,

  // Token 管理方法
  getToken() {
    return uni.getStorageSync(AUTHORIZATION)
  },

  setToken(token) {
    uni.setStorageSync(AUTHORIZATION, token)
  },

  clearToken() {
    return uni.removeStorageSync(AUTHORIZATION)
  },

  // 用户信息管理方法
  getUserInfo() {
    return uni.getStorageSync(USER_INFO)
  },

  setUserInfo(userInfo) {
    uni.setStorageSync(USER_INFO, userInfo)
  },

  clearUserInfo() {
    return uni.removeStorageSync(USER_INFO)
  }
}

// 工具函数
export const showToast = (title) => {
  uni.showToast({
    icon: 'none',
    title: title
  })
}

export const getToken = () => {
  return uni.getStorageSync(AUTHORIZATION)
}

export const setToken = (token) => {
  uni.setStorageSync(AUTHORIZATION, token)
}

export const clearToken = () => {
  return uni.removeStorageSync(AUTHORIZATION)
}

export const getUserInfo = () => {
  return uni.getStorageSync(USER_INFO)
}

export const setUserInfo = (userInfo) => {
  uni.setStorageSync(USER_INFO, userInfo)
}

export const clearUserInfo = () => {
  return uni.removeStorageSync(USER_INFO)
}

export const toLink = (url) => {
  uni.navigateTo({
    url: url
  })
}

export const toRedirect = (url) => {
  uni.redirectTo({
    url: url
  })
}

export const toReLaunch = (url) => {
  uni.reLaunch({
    url: url
  })
}

export const toSwitch = (url) => {
  uni.switchTab({
    url: url
  })
}

export const toBack = () => {
  uni.navigateBack({
    delta: 1
  })
}
